<template>
  <div>
    
    <canvas @click="change" width="150" height="50" id="erwei"></canvas>
  </div>
</template>

<script>
let pen;
let width1
let height1
export default {
  
  methods: {
    drawCanvas() {
       pen = document.getElementById("erwei").getContext("2d");
      
       width1 = document.getElementById("erwei").clientWidth;
       height1 = document.getElementById("erwei").clientHeight;
      pen.clearRect(0, 0, 200, 50);
      this.bgColor();
      this.drawLine(10)
      this.drawArc(5)
      this.drawText();
    },
    // 绘制矩形
    bgColor() {
      pen.beginPath();
      pen.fillStyle =this.randomColor();
      pen.fillRect(0, 0, 200, 50);
    },
    // 绘制线条
    drawLine(num) {
      for (let index = 0; index < num; index++) {
        pen.beginPath();
        pen.strokeStyle = this.randomColor();
        pen.moveTo(this.randomPositionX(), this.randomPositionY());
        pen.lineTo(this.randomPositionX(), this.randomPositionY());
        pen.stroke();
      }
    },
    // 绘制圆
    drawArc(num) {
      for (let index = 0; index < num; index++) {
        pen.beginPath();
        pen.fillStyle = this.randomColor();
        pen.arc(
          this.randomPositionX(),
          this.randomPositionY(),
          Math.random() * 5 + 3,
          0,
          (Math.PI / 180) * 360
        );
        pen.fill();
        pen.stroke();
      }
    },
    // 产生文本
    drawText() {
      let randomText = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
    let sureText=''
      for (let index = 0; index < 4; index++) {
        let sum = parseInt(Math.random() * randomText.length);
        pen.save();
        pen.font = parseInt(Math.random() * 30 + 15) + "px 宋体";
        pen.fillStyle =this.randomColor();
        // pen.rotate((Math.PI / 180) * 10);
        pen.fillText(randomText[sum], (width1 / 4) * index, height1 / 2 + 15);
        pen.restore();
        
        sureText+=randomText[sum]
      }
      // console.log(sureText);
      this.$emit('code',sureText)
    },
    // 随机颜色
    randomColor() {
      let r = parseInt(Math.random() * 256);
      let g = parseInt(Math.random() * 256);
      let b = parseInt(Math.random() * 256);
      return `rgb(${r},${g},${b})`;
    },
    // 随机位置
    randomPositionX() {
      let x = Math.random() * document.querySelector("#erwei").clientWidth;
      return x;
    },
    randomPositionY() {
      let y = Math.random() * document.querySelector("#erwei").clientHeight;
      return y;
    },
    change(){
        this.drawCanvas()
    }
  },
  mounted() {
    this.drawCanvas()
  },
};
</script>

<style lang='scss' scoped>

</style>